package org.ailuoli.guard.api.controller;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.ailuoli.guard.domain.entity.Platform;
import org.ailuoli.guard.domain.enums.DeleteEnum;
import org.ailuoli.guard.domain.enums.PlatformTypeEnum;
import org.ailuoli.guard.domain.enums.StatusEnum;
import org.ailuoli.guard.domain.service.PlatformService;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.tools.bedrock.http.resp.RR;
import org.tools.bedrock.http.resp.v2.R;
import org.tools.bedrock.util.BaseUtils;

/**
 * @author sander
 * @date 2025/02/0
 **/
@Slf4j
@RestController
@RequestMapping("platform")
@RequiredArgsConstructor
public class PlatformController {

    private final PlatformService platformService;

    @PostMapping
    public RR list() {
        return R.ok(platformService.lambdaQuery()
                .eq(Platform::getDeleted, DeleteEnum.FALSE.value())
                .list());
    }

    @PostMapping("add")
    public RR add(@RequestBody Platform platform) {
        if (BaseUtils.isEmpty(platform.getType())) {
            platform.setType(PlatformTypeEnum.DEFAULT.value());
        }
        return R.ok(platformService.save(platform));
    }

    @PutMapping
    public RR edit(@RequestBody Platform platform) {
        Assert.notNull(platform.getId(), "id is null");
        return R.ok(platformService.updateById(platform));
    }

    @DeleteMapping
    public RR delete(@RequestParam("id") Long id) {
        Assert.notNull(id, "id is null");
        return R.ok(platformService.lambdaUpdate()
                .set(Platform::getDeleted, DeleteEnum.TRUE.value())
                .eq(Platform::getId, id)
                .update());
    }

    @PutMapping("status")
    public RR status(@RequestParam("id") Long id, @RequestParam("status") String status) {
        Assert.notNull(id, "id is null");
        Assert.notNull(status, "status is null");

        StatusEnum statusEnum = StatusEnum.of(status);
        if (StatusEnum.ERROR.equals(statusEnum)) {
            return R.fail(String.format("status: %s 不合法", statusEnum.value()));
        }

        return R.ok(platformService.lambdaUpdate()
                .set(Platform::getStatus, statusEnum.value())
                .eq(Platform::getId, id)
                .update());
    }

}
